   //
//  NetWorkTools.swift
//  MySinaWeibo
//
//  Created by apple on 15/11/3.
//  Copyright © 2015年 baidu. All rights reserved.
//

import UIKit
import AFNetworking

/// 错误的类别标记
private let LNErrorDomainName = "com.baidu.error.network"
   
   /// 网络访问错误信息 - 枚举，是定义一组类似的值
   /// Swift 中枚举可以定义函数和属性，跟'类有点像'
   private enum LNNetworkError: Int {
    
    case emptyDataError = -1
    case emptyTokenError = -2
    
   /// 错误描述
    private var errorDescrption: String {
    
        switch self {
            
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token 为空"
        }
        
    }
    private func error() -> NSError {
    
        return NSError(domain: LNErrorDomainName, code: rawValue, userInfo: [LNErrorDomainName: errorDescrption])
    }
   }
   
class NetWorkTools: AFHTTPSessionManager {
    
//    单例
    static let sharedTools: NetWorkTools = {
        
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = NetWorkTools(baseURL: baseURL)
        
//        设置数据解析数据类型
//        tools.responseSerializer.acceptableContentTypes = NSSet(object:"application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        tools.responseSerializer.acceptableContentTypes.insert("text/plain")
        return tools
    }()
    
//    MARK: - 加载用户数据
    func loadUserInfo(uid: String, finished: LNNetFinishedCallBack) {
        
//        判断token是否存在
        if UserAccount.sharedAccount?.access_token == nil {
            
            let error = LNNetworkError.emptyTokenError.error()
            print(error)
            finished(result: nil, error: error)
            
            return
        }
        let urlString = "2/users/show.json"
        let params: [String: AnyObject] = ["access_token": UserAccount.sharedAccount!.access_token!, "uid": uid]
        
//        发送网络请求
//        requestGET(urlString, params: params) { (result, error) -> () in
//            print(result)
//        }
        requestGET(urlString, params: params, finished: finished)
        
    }
    
    

//    MARK: - OAuth授权
//    App Key：2007160636
//    App Secret：87cc67e25e8bfb7b564e461cbbcd41ba
    private let clientId = "2007160636"
    private let appSecret = "87cc67e25e8bfb7b564e461cbbcd41ba"
     /// 回调地址
     let redirectUri = "http://www.baidu.com"
//    MARK: -类型定义
    typealias LNNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()
    
//    返回OAuth授权地址
    func oauthUrl() -> NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
/// 加载Token
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            
            "client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri
        ]
        
        requestPOST(urlString, params: params, finished: finished)
//        
//        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
////            print(JSON)
//            finished(result: JSON as? [String: AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                print(error)
//                finished(result: nil, error: error) 
//        }
    }

//    MARK: - 封装 AFN 网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
/// 网络回调类型别名
//    typealias LNNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()
    
    /// GET 请求
    ///
    /// - parameter urlString: URL地址
    /// - parameter params:    参数字典
    /// - parameter finished:  完成回调
    private func requestGET(urlString: String, params: [String: AnyObject], finished: LNNetFinishedCallBack) {
        
        GET(urlString, parameters: params, success: { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
                
//                有结果的回调
                finished(result: result, error: nil)
            
            } else {
            
//                没有错误，没有结果
                print("没有数据 GET Request \(urlString)")
//                /**
//                domain:错误的范围/大类别，定义一个常量字符串
//                code:错误代码，有些公司会专门定义一个特别大的.h，定义所有的错误编码，通常是负数
//                userInfo：可以传递一些附件的错误信息
//                */
//                let error = NSError(domain: LNErrorDomainName, code: -1, userInfo: ["errorMessage": "空数据"])
                finished(result: nil, error: LNNetworkError.emptyDataError.error())
            }
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
    
    private func requestPOST(urlString: String, params: [String: AnyObject], finished: LNNetFinishedCallBack) {
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            if let result = JSON as? [String: AnyObject] {
                
                //                有结果的回调
                finished(result: result, error: nil)
                
            } else {
                
                //                没有错误，没有结果
                print("没有数据 POST Request \(urlString)")
                
                finished(result: nil, error: LNNetworkError.emptyDataError.error())
            }
            }) { (_, error) -> Void in
                print(error)
                finished(result: nil, error: error)
        }
    }
    
}






































